from game_agent import GameAgent
from agent_english import AgentEnglish
from agent_powers import AgentPowers
from random import randint
from match import runMatch
from anytime_alpha_beta import AnyTimeAlphaBetaSearch
from linear import linearEvaluator 
from time import strftime

class RandomAgent(GameAgent):
    def move(self, game_state):
            successors = game_state.getSuccessors().keys()
            return successors[randint(0,len(successors)-1)]

    def setup(self, player, game_state, turn_time_limit, setup_time_limit):
        pass

class AgentBond(GameAgent):
    '''
    AlphaBeta
    utility: linearEvaluator
    '''
    def move(self, game_state):
        return self.alphaBeta.search(game_state)

    def setup(self, player, game_state, turn_time_limit, setup_time_limit):
        self.player = player
        u = lambda state: self.utility(state)
        self.alphaBeta = AnyTimeAlphaBetaSearch(self.player, 2, u, turn_time_limit)
    
    def utility(self, state):
        return linearEvaluator(self, state, self.player)

def battle(agent1, agent2): 
    boardSizes = [5, 10, 20, 30]
    turnLimits = [70]
    turnTimes = [0.2, 5, 10, 20] 
    setupTime = 0.1
    results = []
    place = 0
    for size in boardSizes:
        for turnLimit in turnLimits:
            for timeLimit in turnTimes:
                results.append(tuple([runMatch(agent1, agent2, size, \
                                     turnLimit, timeLimit, setupTime)] + [size, turnLimit]))
                print "Done with "+str((size,turnLimit,timeLimit)), strftime(' %H:%M:%S '), results[place]
                place += 1
    return results

def tournament(agent1, agent2): 
    boardSizes = [12]
    turnLimits = [100]
    turnTimes = [10] 
    setupTime = 0.1
    results = []
    place = 0
    for size in boardSizes:
        for turnLimit in turnLimits:
            for timeLimit in turnTimes:
                results.append(tuple([runMatch(agent1, agent2, size, \
                                     turnLimit, timeLimit, setupTime)] + [size, turnLimit]))
                print "Done with "+str((size,turnLimit,timeLimit)), strftime(' %H:%M:%S '), results[place]
                place += 1
    return results

def logResults(agent1, agent2, filename, type):
    if "battle" == type: results = battle(agent1, agent2)
    else: results = tournament(agent1, agent2)
    
    for line in results:
        print line
        f = open(filename,"a")
        f.write("Agent1 White\tAgent2 Black\tAgent1 Black\tAgent2 White\t\tBoard Size\tTime Limit\n")
        for cell in line[0]:
            f.write(str(cell)+"\t")
        f.write("\t"+str(line[1])+"\t")
        f.write(str(line[2])+"\n")
        f.close()